package Offer53_34;

/**
 * @author 23737
 * @Time 2021.9.6
 * 在排序数组中查找元素的第一个和最后一个位置
 */
public class Test34 {
    public static void main(String[] args) {
        int[] array = new int[]{5, 7, 7, 8, 8, 10};
        Solution solution = new Solution();
        int[] ints = solution.searchRange(array, 8);
        System.out.println(ints[0]);
        System.out.println(ints[1]);
    }
}

/*二分查找来实现*/
class Solution {
    public int[] searchRange(int[] nums, int target) {
        if (nums.length == 0) {
            return new int[]{-1, -1};
        }
        //查找元素开始的位置
        int i = 0, j = nums.length - 1;
        while (i < j) {
            int mid = (i + j) / 2;
            if (nums[mid] >= target) {
                j = mid;
            } else {
                i = mid + 1;
            }
        }
//        count[1] = j;
        //查找失败
        if (nums[j] != target) return new int[]{-1, -1};
        //把开始的元素进行复制
        int Left = j;
        //查找元素结束的位置
        i = 0;
        j = nums.length - 1;
        while (i < j) {
            int mid = (i + j + 1) / 2;
            if (nums[mid] <= target) {
                i = mid;
            } else {
                j = mid - 1;
            }
        }
        return new int[]{Left, j};
    }
}
